package com.zhiqian.serializer.impl;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.zhiqian.serializer.CommonSerializer;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Slf4j
public class HessianSerializer implements CommonSerializer {
    @Override
    public byte[] serialize(Object obj) {
        try(ByteArrayOutputStream bos=new ByteArrayOutputStream()){
            Hessian2Output output=new Hessian2Output(bos);
            output.writeObject(obj);
            output.flushBuffer();
            return bos.toByteArray();
        }catch (IOException e){
            log.error("序列化出现错误：{}",e);
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Object deserialize(byte[] bytes, Class<?> clazz) {
        try(ByteArrayInputStream bis=new ByteArrayInputStream(bytes)){
            Hessian2Input input = new Hessian2Input(bis);
            return input.readObject(clazz);
        }catch (IOException e){
            log.error("反序列化出现错误：{}",e);
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getCode() {
        return 2;
    }
}
